import BaseObject from "../base/BaseObject";
import GameTimeObserver from "./GameTimeObserver";
import GameTimer from "./GameTimer";

export default class GameTimeManager extends BaseObject {

    private time: number = 0;
    //以秒为单位的观察者。
    private secondObserverList: GameTimeObserver[] = [];

    // private gameTimer: GameTimer;

    private static ins: GameTimeManager;


    private dt:number = 0;

    private interval:number = 1;


    constructor() {
        super();
        // this.gameTimer = new GameTimer();
        // this.gameTimer.addListener(this.update, this)
    }

    static instance(): GameTimeManager {
        if (!this.ins) {
            this.ins = new GameTimeManager();
        }
        return this.ins;
    }


    start(){
        // this.gameTimer.start(1)
    }

    stop(){
        // this.gameTimer.stop();
    }

    pause(){
        // this.gameTimer.pause();
    }

    resume(){
        // this.gameTimer.resume();
    }



    setTime(time: number) {
        this.time = time;
        this.dt = 0;
    }


    getTime() {
        return this.time;
    }

    has(observer:GameTimeObserver){
        for (let index = 0; index < this.secondObserverList.length; index++) {
            const element = this.secondObserverList[index];
            if(element == observer){
                return true;
            }
        }
        return false;
    }

    addTimeListener(observer: GameTimeObserver) {
        if(!this.has(observer)){
            this.secondObserverList.push(observer);
        }
        
    }

    removeTimeListener(observer: GameTimeObserver) {
        for (let index = 0; index < this.secondObserverList.length; index++) {
            const element = this.secondObserverList[index];
            if (observer === element) {
                this.secondObserverList.splice(index, 1);
                break;
            }
        }
    }

    update(dt: number) {
        this.dt += dt;
        if(this.dt >= this.interval){
            this.time += this.interval;
            this.dt -= this.interval;
            for (let index = 0; index < this.secondObserverList.length; index++) {
                const element: GameTimeObserver = this.secondObserverList[index];
                if (this.time % element.getTime() == 0) {
                    element.excute();
                }
            }            
        }
    }

    clear() {
        this.secondObserverList = [];
    }
}
